package com.example;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-07-03
 * Time: 19:31
 */
@RestController
@RequestMapping("/captcha")
public class HuToolCaptchaController {

    @GetMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100,4,300);
        try {
            //图形验证码写出，输出到页面，也就是说生成的图片路径是/captcha/get
            lineCaptcha.write(response.getOutputStream());//getOutputStream方法有异常处理，所以需要try catch
            System.out.println(lineCaptcha.getCode());
            //将验证码信息存储到session中
            session.setAttribute("captcha", lineCaptcha.getCode());
            //为了实现验证码的时效性，将创建验证码时间存储到session中
            session.setAttribute("captchaTime",new Date());
            System.out.println(session.getAttribute("captchaTime"));
            //关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("/check")
    public Boolean checkCaptcha(String captcha, HttpSession session){
        //1.检验前端输入的验证码是否有效
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        //2.获取session中的验证码和时间
        String savedCaptcha = (String) session.getAttribute("captcha");
        Date savedTime = (Date) session.getAttribute("captchaTime");
        //3.开始校验验证码和时间是否超时
        if(captcha.equalsIgnoreCase(savedCaptcha)){
            //忽略验证码大小写，验证码正确，则进行检验时间是否满足1分钟之内
            //因为方法返回的时间戳单位是毫米，所以要转换单位
            if(savedTime == null || new Date().getTime() - savedTime.getTime() < 1000 * 60){
                //验证码有效
                return true;
            }
            return false;
        }
        return false;
    }
}
